package com.hp.fremarker.web.server;

import com.hp.fremarker.web.servlet.DispatcherServlet;
import org.apache.catalina.Context;
import org.apache.catalina.LifecycleException;
import org.apache.catalina.core.StandardContext;
import org.apache.catalina.startup.Tomcat;

/**
 * @author dongxing
 **/
public class TomcatServer {

    private Tomcat tomcat;

    private String[] args;

    public TomcatServer(String[] args) {
        this.args = args;
    }

    public void startServer() throws LifecycleException {
        tomcat = new Tomcat();
        tomcat.setPort(6699);
        tomcat.start();

        // 设置context
        Context context = new StandardContext();
        context.setPath("");
        //生命周期监听器
        context.addLifecycleListener(new Tomcat.FixContextListener());

        DispatcherServlet testServlet = new DispatcherServlet();
        //支持异步
        tomcat.addServlet(context, "dispatcherServlet", testServlet).setAsyncSupported(true);

        //路径映射，相当于访问的路径是什么
        context.addServletMappingDecoded("/","dispatcherServlet");

        // tomcat将context加载进去
        tomcat.getHost().addChild(context);

        //tomcat的等待线程
        Thread awaitThread = new Thread("tomcat_await_name") {
            @Override
            public void run() {
                TomcatServer.this.tomcat.getServer().await();

            }
        };
        awaitThread.setDaemon(false);
        awaitThread.start();
    }
}
